<template>
  <div ref="statsRef"></div>
  <div ref="containerRef" class="container"></div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue';
import {
  AxesHelper,
  Color,
  PerspectiveCamera,
  PlaneGeometry,
  Scene,
  WebGLRenderer,
  Mesh,
  BoxGeometry,
  SphereGeometry,
  SpotLight, MeshLambertMaterial
} from 'three';
import Stats from "stats.js"


/**
 * 性能统计
 */
const statsRef = ref<HTMLDivElement>();
const stats = new Stats()
// stats.dom.style.top = '50px'
stats.showPanel(0)   // 就是不写，这个框体也会默认显示

const containerRef = ref<HTMLDivElement>();
// 创建一个场景
const scene = new Scene();
// 设置摄像机位置
const camera = new PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// 设置摄像机朝向
camera.position.set(-30, 40, 30);
camera.lookAt(scene.position);

const renderer = new WebGLRenderer();

renderer.setClearColor(new Color(0xeeeeee));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true

/**
 * 光源设置
 */
const spotLight = new SpotLight(0xffffff,3000)
spotLight.position.set(-20, 30, -10);
spotLight.castShadow = true
scene.add(spotLight)

/**
 * 引入 x,y,z 线
 */
const axes = new AxesHelper(20);
scene.add(axes);

/**
 * 引入地板
 */
const planeGeometry = new PlaneGeometry(60, 20);
const meshBasicMaterial = new MeshLambertMaterial({color: 0xcccccc});
const plane = new Mesh(planeGeometry, meshBasicMaterial);
plane.receiveShadow=true
plane.rotation.x = -0.5 * Math.PI;
plane.position.x = 15;
plane.position.y = 0;
plane.position.z = 0;
scene.add(plane);


/**
 * 引入正方体
 */

const cubeGeometry = new BoxGeometry(4, 4, 4);

const cubeMaterial = new MeshLambertMaterial({
  color: 0xff0000,
  wireframe: false,
});

const cube = new Mesh(cubeGeometry, cubeMaterial);
cube.castShadow=true
cube.position.set(2, 2, 2);
scene.add(cube);

/**
 * 引入球体
 */
const sphereGeometry = new SphereGeometry(4);

const sphereMaterial = new MeshLambertMaterial({
  color: 0x7777ff,
  wireframe: false,
});

const sphere = new Mesh(sphereGeometry, sphereMaterial);
sphere.castShadow = true;
sphere.position.x = 20;
sphere.position.y = 4;
sphere.position.z = 2;
scene.add(sphere);

/**
 * 添加动作
 */
let step = 0;
function renderScene() {
  // 统计性能
  stats.update()
  cube.rotation.x += 0.02;
  cube.rotation.y += 0.02;
  cube.rotation.z += 0.02;

  //改变长宽
  // cube.scale.x += 0.01;

  step += 0.04;
  sphere.position.x = 20 + 10 * Math.cos(step);
  sphere.position.y = 2 + 10 * Math.abs(Math.sin(step));

  requestAnimationFrame(renderScene)
  renderer.render(scene,camera)
}
renderScene()

onMounted(() => {
  // 开机渲染
  statsRef.value?.append(stats.dom)
  containerRef.value?.appendChild(renderer.domElement);
  renderer.render(scene, camera);
});
</script>

<style scoped>
</style>
